package com.neusoft.neuiotms.dcam.fixed.converter;

import java.util.Date;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import com.neusoft.bizcore.auth.common.bean.UserBean;
import com.neusoft.bizcore.web.dto.AbstractConverter;
import com.neusoft.neuiotms.common.service.SerialNumberService;
import com.neusoft.neuiotms.dcam.fixed.dto.InventoryPlanDTO;
import com.neusoft.neuiotms.dcam.fixed.model.InventoryPlan;
import com.neusoft.neuiotms.dcam.fixed.repository.InventoryPlanRepository;

@Component
public class InventoryPlanConverter extends AbstractConverter<InventoryPlan, InventoryPlanDTO> {

    @Autowired
    private InventoryPlanRepository inventoryPlanRepository;
    @Autowired
    private InventoryDutyConverter inventoryDutyConverter;
    @Autowired
    private SerialNumberService planCodeGenerator;

    @Override
    public InventoryPlan toModel(final InventoryPlanDTO dto) {
        InventoryPlan model;
        if (dto.isNew()) {
            model = new InventoryPlan();
            model.setCode(this.planCodeGenerator.generateSerialNumberByModelCode("PD_CODE"));
        } else {
            model = this.inventoryPlanRepository.getOne(dto.getId());
            model.setCode(dto.getCode());
        }
        model.setName(dto.getName());
        model.setUserId(dto.getUserId());
        model.setUserName(dto.getUserName());
        model.setUpdateTime(new Date());
        model.setStatus(dto.getStatus());
        model.setStartDate(dto.getStartDate());
        model.setEndDate(dto.getEndDate());
        model.setRemarks(dto.getRemarks());
        model.setBelongs(dto.getBelongs());

        return model;
    }

    @Override
    public InventoryPlanDTO toDTO(final InventoryPlan model, final boolean forListView) {

        final InventoryPlanDTO dto = new InventoryPlanDTO();
        dto.setId(model.getId());
        dto.setName(model.getName());
        dto.setCode(model.getCode());
        dto.setUserId(model.getUserId());
        dto.setUserName(model.getUserName());
        dto.setUpdateTime(model.getUpdateTime());
        dto.setStatus(model.getStatus());
        dto.setStartDate(model.getStartDate());
        dto.setEndDate(model.getEndDate());
        dto.setRemarks(model.getRemarks());
        dto.setBelongs(model.getBelongs());

        if (forListView) {
            if ((model.getDutyItems() != null) || !model.getDutyItems().isEmpty()) {
                model.getDutyItems().stream().map(ele -> this.inventoryDutyConverter.toDTO(ele)).filter(m -> null != m)
                        .forEach(dto.getDutyItems()::add);
            }
        }
        return dto;
    }

    public InventoryPlanDTO merge(final InventoryPlanDTO dto, final UserBean user) {
        dto.setUserId(user.getUserId());
        dto.setUserName(user.getName());
        return dto;
    }
}
